package cn.chanel.mall.controller;

import cn.chanel.mall.constant.CookieName;
import cn.chanel.mall.entity.User;
import cn.chanel.mall.service.UserService;
import cn.chanel.mall.utils.CookieUtil;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class LoginController {

    @Resource
    private UserService userService;

    @PostMapping("login")
    public ModelAndView userLogin(@RequestParam String email,
                                     @RequestParam String password,
                                     HttpServletResponse servletResponse,
                                     Map<String, Object> map){
        if(!(StringUtils.hasText(email) && StringUtils.hasText(password))){
            return new ModelAndView("redirect:/user/login?failed=true");
        }
        final User user = userService.loginOrRegister(email, password);
        if(user != null){
            CookieUtil.set(servletResponse, CookieName.USER_LOGIN, user.getId(), 3600);
            map.put("userInfo", user);
            // 登录成功返回主页
            return new ModelAndView("redirect:/goods/default", map);
        }else {
            return new ModelAndView("redirect:/user/login?failed=true");
        }
    }

    @GetMapping("login")
    public ModelAndView getLoginPage(@RequestParam(required = false, defaultValue = "false") boolean failed,
                                     Map<String, Object> map){
        map.put("loginFailed", failed);
        return new ModelAndView("login", map);
    }

    @GetMapping("logout")
    public ModelAndView loginOut(@CookieValue(name = CookieName.USER_LOGIN, required = false) String userId,
                                 HttpServletResponse response){
        // Clear Cookie
        CookieUtil.set(response, CookieName.USER_LOGIN, null, 0);
        return new ModelAndView("redirect:/user/login?failed=false");
    }
}
